package com.sinosoft.aspectj;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hyy85
 * @version 1.0
 * @date: 13/6/2018 上午 10:59<br/>
 * @description 切面
 * @since 1.8
 */
@Aspect
@Component
public class HttpAspect {

    private Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public * com.sinosoft.controller.*.*(..))")
    public void log() {}

    @Before("log()")
    public void doBeafore(JoinPoint joinPoint) {
        logger.info("============================进入接口之前========================");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        logger.info("请求的url为: {} ",request.getRequestURL());
        //method
        logger.info("请求的方式为: {} ",request.getMethod());
        //ip
        logger.info("请求的ip为: {} ",request.getRemoteAddr());
        //class method
        logger.info("请求的类方法为: {} ",joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        //params
        logger.info("请求的参数为: {} ",joinPoint.getArgs());
    }

    @After("log()")
    public void doAfter() {
        logger.info("============================进入接口之后========================");
    }

    @AfterReturning(pointcut = "log()",returning = "data")
    public void doAfterReturning(Object data) {
        logger.info("response = {}",data);
    }
}
